package com.sany.cxp.RabbitMQ.topics;

import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @Author: Thomas
 * @Date: 2024-01-07  10:54:59
 * @Description:
 */
@Slf4j
public class Consumer {
    public static void main(String[] args) {
        new Thread(() -> getMessage("queue01")).start();
        new Thread(() -> getMessage("queue02")).start();
        new Thread(() -> getMessage("queue03")).start();
        // 如果rabbitmq没有这个队列会报错的
        // new Thread(() -> getMessage("queue048768")).start();
    }

    public static void getMessage(String queue){
        // 1. 创建连接工程
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("120.26.196.115");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        // 设置虚拟机节点
        connectionFactory.setVirtualHost("/");

        Connection connection = null;
        Channel channel = null;
        try {
            // 2. 创建连接
            connection = connectionFactory.newConnection("消费者");
            // 3. 通过连接获取通道
            channel = connection.createChannel();
            // 4. 接受消息【持续性接受的过程，不会关闭程序】
            channel.basicConsume(queue, true, new DeliverCallback() {
                @Override
                public void handle(String s, Delivery delivery) throws IOException {
                    log.info("{} -- 得到消息 -- {}", queue, new String(delivery.getBody(), "UTF-8"));
                }
            }, new CancelCallback() {
                @Override
                public void handle(String s) throws IOException {
                    System.out.println("接收消息失败了~");
                }
            });

            System.out.println("开始接收消息");
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 7. 关闭通道
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 8. 关闭连接
            if (connection != null && connection.isOpen()) {
                try {
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
